/**
 * 进度缓存管理器
 * 避免重复的API调用，提升性能
 */

interface ProgressCacheItem {
  data: any;
  timestamp: number;
  expiry: number; // 缓存过期时间（毫秒）
}

class ProgressCacheManager {
  private cache: Map<string, ProgressCacheItem> = new Map();
  private defaultExpiry: number = 5 * 60 * 1000; // 默认5分钟过期

  /**
   * 生成缓存键
   */
  private generateKey(courseId: number, lessonId: number, type: string): string {
    return `${type}_${courseId}_${lessonId}`;
  }

  /**
   * 设置缓存
   */
  set(courseId: number, lessonId: number, type: string, data: any, expiry?: number): void {
    const key = this.generateKey(courseId, lessonId, type);
    const item: ProgressCacheItem = {
      data,
      timestamp: Date.now(),
      expiry: expiry || this.defaultExpiry
    };
    
    this.cache.set(key, item);
    console.log(`📦 缓存进度数据: ${key}`);
  }

  /**
   * 获取缓存
   */
  get(courseId: number, lessonId: number, type: string): any | null {
    const key = this.generateKey(courseId, lessonId, type);
    const item = this.cache.get(key);

    if (!item) {
      return null;
    }

    // 检查是否过期
    if (Date.now() - item.timestamp > item.expiry) {
      this.cache.delete(key);
      console.log(`🗑️ 清除过期缓存: ${key}`);
      return null;
    }

    console.log(`✅ 使用缓存数据: ${key}`);
    return item.data;
  }

  /**
   * 删除特定缓存
   */
  delete(courseId: number, lessonId: number, type: string): void {
    const key = this.generateKey(courseId, lessonId, type);
    this.cache.delete(key);
    console.log(`🗑️ 删除缓存: ${key}`);
  }

  /**
   * 清除所有缓存
   */
  clear(): void {
    this.cache.clear();
    console.log('🗑️ 清除所有进度缓存');
  }

  /**
   * 清除过期缓存
   */
  clearExpired(): void {
    const now = Date.now();
    const expiredKeys: string[] = [];

    this.cache.forEach((item, key) => {
      if (now - item.timestamp > item.expiry) {
        expiredKeys.push(key);
      }
    });

    expiredKeys.forEach(key => {
      this.cache.delete(key);
    });

    if (expiredKeys.length > 0) {
      console.log(`🗑️ 清除 ${expiredKeys.length} 个过期缓存`);
    }
  }

  /**
   * 获取缓存统计信息
   */
  getStats(): {
    totalItems: number;
    totalSize: number;
    expiredItems: number;
  } {
    const now = Date.now();
    let expiredItems = 0;
    let totalSize = 0;

    this.cache.forEach((item) => {
      if (now - item.timestamp > item.expiry) {
        expiredItems++;
      }
      totalSize += JSON.stringify(item.data).length;
    });

    return {
      totalItems: this.cache.size,
      totalSize,
      expiredItems
    };
  }

  /**
   * 设置默认过期时间
   */
  setDefaultExpiry(expiry: number): void {
    this.defaultExpiry = expiry;
  }
}

// 创建全局实例
export const progressCache = new ProgressCacheManager();

// 定期清理过期缓存
setInterval(() => {
  progressCache.clearExpired();
}, 60000); // 每分钟清理一次

// 页面卸载时清理缓存
if (typeof window !== 'undefined') {
  window.addEventListener('beforeunload', () => {
    progressCache.clear();
  });
}

/**
 * 缓存类型常量
 */
export const CACHE_TYPES = {
  LESSON_PROGRESS: 'lesson_progress',
  COURSE_PROGRESS: 'course_progress',
  RESUME_POSITION: 'resume_position'
} as const;

/**
 * 缓存过期时间常量
 */
export const CACHE_EXPIRY = {
  SHORT: 2 * 60 * 1000,      // 2分钟
  MEDIUM: 5 * 60 * 1000,     // 5分钟
  LONG: 15 * 60 * 1000,      // 15分钟
  SESSION: 60 * 60 * 1000    // 1小时
} as const;
